const config = {
    type: 1,

}
function submitForm() {
    details = []
    dataToSend = null;
    console.log('点击了')
    // 获取关键字输入框的值
    var keyword = document.getElementById("keyword").value;
    // 获取服务器输入框的值
    var server = document.getElementById("server").value;
    // 这里可以做一些处理，比如验证输入等
    // 输出获取到的值，你可以根据需要修改
    console.log("关键字: " + keyword);
    console.log("服务器: " + server);
    // 在这里可以将获取到的值提交到服务器
    window.open('https://www.xiaohongshu.com/search_result?keyword=' + keyword)
    return false;
}
async function sendData() {
    if (details.length == dataToSend.data.length) {
        var catalogue = document.getElementById("catalogue").value + '系列';
        var keyword = document.getElementById("keyword").value;
        console.log('done')
        console.log('全部数据', details);

        let chunk = chunkArray(details, 50);
        for (let index = 0; index < chunk.length; index++) {
            const data = chunk[index];
            let params = {
                type: document.querySelector('#downloadType').value,
                catalogue,
                key: keyword,
                data
            }

            console.log(params, '传给服务器的数据')
            await sendDataToServer(params)
        }

    }
}
function chunkArray(array, chunkSize) {
    let index = 0;
    let chunks = [];

    while (index < array.length) {
        let chunk = array.slice(index, index + chunkSize);
        chunks.push(chunk);
        index += chunkSize;
    }

    return chunks;
}

let btnOutPut = document.querySelector(".submit");
let resetCurData = document.querySelector(".resetCurData");
btnOutPut.onclick = submitForm;
resetCurData.onclick = sendData;
let details = [];
let dataToSend = null;

function openPage(id, index) {
    console.log('openPage 执行了')
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            window.open('https://www.xiaohongshu.com/explore/' + id);
            console.log(index, details, length == details.length, 'index')
            resolve()
        }, 4000 + (Math.random() * 100))
    })
}
async function getDetail() {
    var keyword = document.getElementById("keyword").value;
    let key = dataToSend.key;
    let ids = dataToSend.data;
    let length = ids.length;
    console.log(length, ids, 'getDetail')
    for (let index = 0; index <= length; index++) {

        const id = ids[index];
        console.log(index, id, 'getDetail index')
        if (id) {
            await openPage(id, index)
        }

    }
}
chrome.runtime.onMessage.addListener(
    async function (request, sender, sendResponse) {
        console.log(request, sender, sendResponse);
        if (request.greeting === 'SearchPageReady') {
            console.log('小红书搜索爬取笔记id就绪')
            // chrome.tabs.sendMessage(sender.tab.id, { greeting: '"StartCollectingNoteIds"' })
            var keyword = document.getElementById("keyword").value;
            sendResponse({ key: keyword });
        }
        if (request.greeting === 'SearchPageReadyEnd') {
            console.log('笔记id 已经ok，准备爬取详情', request.data);
            // let a = request.data;
            // a.data = a.data.splice(0, 2);
            dataToSend = request.data;
            getDetail()
        }
        if (request.greeting === 'returnDetail') {
            console.log('返回详情', request.data);
            details.push(request.data)
            console.log(details.length == dataToSend.data.length, details.length, dataToSend.data.length)
            sendData()
            sendResponse();
        }
        // console.log(request, sender, sendResponse, '收到消息');
        // console.log(sender.tab ?
        //     "from a content script:" + sender.tab.url :
        //     "from the extension");
        // if (request.greeting.indexOf("hello") !== -1) {
        //     sendResponse({ farewell: "goodbye" });
        // }
    });
// chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
//     chrome.tabs.sendMessage(
//         tabs[0].id,
//         { greeting: "hello，我是后台，主动发消息给content-script" },
//         function (response) {
//             console.log(response.farewell);
//         }
//     );
// });

function sendDataToServer(data) {
    // 设置fetch选项
    const requestOptions = {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(data)
    };

    // 发起POST请求
    let url = document.getElementById("server").value;
    return new Promise((resolve, reject) => {
        fetch(url, requestOptions)
            .then(response => {
                // 检查响应状态
                if (!response.ok) {
                    throw new Error('Network response was not ok');
                }
                // 解析JSON格式的响应数据

                return response.json();
            })
            .then(responseData => {
                // 处理接收到的响应数据
                console.log('Received response from server:', responseData);
                resolve(responseData)
            })
            .catch(error => {
                resolve()
                // 处理错误
                console.error('There was a problem with the fetch operation:', error);
            });
    })

}


